import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:equatable/equatable.dart';

import 'joke.dart';

// Events
abstract class JokeEvent extends Equatable {
  const JokeEvent();

  @override
  List<Object> get props => [];
}

class LoadJoke extends JokeEvent {
  const LoadJoke();
}

class RefreshJoke extends JokeEvent {
  const RefreshJoke();
}

// States
abstract class JokeState extends Equatable {
  const JokeState();

  @override
  List<Object?> get props => [];
}

class JokeInitial extends JokeState {
  const JokeInitial();
}

class JokeLoading extends JokeState {
  const JokeLoading();
}

class JokeRefreshing extends JokeState {
  const JokeRefreshing(this.currentJoke);

  final Joke currentJoke;

  @override
  List<Object?> get props => [currentJoke];
}

class JokeLoaded extends JokeState {
  const JokeLoaded(this.joke);

  final Joke joke;

  @override
  List<Object?> get props => [joke];
}

class JokeError extends JokeState {
  const JokeError(this.message);

  final String message;

  @override
  List<Object?> get props => [message];
}

// Bloc
class JokeBloc extends Bloc<JokeEvent, JokeState> {
  JokeBloc() : super(const JokeInitial()) {
    on<LoadJoke>(_onLoadJoke);
    on<RefreshJoke>(_onRefreshJoke);
  }

  Future<void> _onLoadJoke(LoadJoke event, Emitter<JokeState> emit) async {
    emit(const JokeLoading());
    try {
      final joke = await fetchRandomJoke();
      emit(JokeLoaded(joke));
    } catch (e) {
      emit(JokeError(e.toString()));
    }
  }

  Future<void> _onRefreshJoke(
    RefreshJoke event,
    Emitter<JokeState> emit,
  ) async {
    // 如果当前有笑话，显示刷新状态
    if (state is JokeLoaded) {
      emit(JokeRefreshing((state as JokeLoaded).joke));
    } else {
      emit(const JokeLoading());
    }

    try {
      final joke = await fetchRandomJoke();
      emit(JokeLoaded(joke));
    } catch (e) {
      emit(JokeError(e.toString()));
    }
  }
}
